'use client';

import React, { useState, useEffect } from 'react';
import ForumMenu from '@/components/forum/ForumMenu';
import ForumRankings from '@/components/forum/ForumRankings';
import { request } from '@/utils/request';

// 排行榜帖子数据类型
interface RankingPost {
  id: string;
  title: string;
  content: string;
  viewCount: number;
  commentCount: number;
  createdAt: string;
  coverUrl: string;
  likeCount: number;
  section: {
    id: string;
    name: string;
    category: {
      id: string;
      name: string;
    };
  };
  author: {
    id: string;
    nickname: string;
    avatar: string;
  };
}

// 排序选项类型
type SortOption = 'viewCount' | 'commentCount' | 'likeCount' | 'createdAt';

const sortOptions = [
  { value: 'viewCount', label: '按浏览量' },
  { value: 'commentCount', label: '按评论数' },
  { value: 'likeCount', label: '按点赞数' },
  { value: 'createdAt', label: '按发布时间' },
];

export default function ForumRankingsPage() {
  const [rankings, setRankings] = useState<RankingPost[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [sortBy, setSortBy] = useState<SortOption>('viewCount');

  // 获取排行榜数据
  const fetchTopPosts = async (sortType: SortOption = 'viewCount') => {
    try {
      setLoading(true);
      setError(null);
      const response = await request(`/forum/rankings?sortBy=${sortType}&limit=20`, {
        method: 'GET',
      });
      
      if (response.code === 0 && response.data) {
        const topPosts = (response.data as RankingPost[]) || [];
        setRankings(topPosts);
      } else {
        setError('获取排行榜数据失败');
      }
    } catch (error) {
      console.error('获取排行榜数据失败:', error);
      setError('网络错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 处理排序变化
  const handleSortChange = (newSort: SortOption) => {
    setSortBy(newSort);
    fetchTopPosts(newSort);
  };

  useEffect(() => {
    fetchTopPosts(sortBy);
  }, []);

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 py-8">
        <div className="bg-white rounded-lg shadow-sm">
          <ForumMenu />
          <div className="p-6">
            {/* 排序选项 */}
            <div className="mb-6">
              <div className="flex items-center justify-between">
                <h1 className="text-xl font-medium text-gray-900">帖子排行榜</h1>
                <div className="flex items-center space-x-2">
                  <span className="text-sm text-gray-600">排序方式：</span>
                  <div className="flex bg-gray-100 rounded-lg p-1">
                    {sortOptions.map((option) => (
                      <button
                        key={option.value}
                        onClick={() => handleSortChange(option.value as SortOption)}
                        className={`px-3 py-1 text-sm rounded-md transition-colors ${
                          sortBy === option.value
                            ? 'bg-white text-cyan-600 shadow-sm'
                            : 'text-gray-600 hover:text-gray-900'
                        }`}
                      >
                        {option.label}
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            {loading ? (
              <div className="flex flex-col justify-center items-center py-16">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-cyan-500 mb-4"></div>
                <div className="text-gray-500">正在加载排行榜数据...</div>
              </div>
            ) : error ? (
              <div className="flex flex-col justify-center items-center py-16">
                <div className="text-red-500 text-lg mb-2">😞</div>
                <div className="text-gray-600 mb-4">{error}</div>
                <button
                  onClick={() => fetchTopPosts(sortBy)}
                  className="px-4 py-2 bg-cyan-500 text-white rounded-lg hover:bg-cyan-600 transition-colors"
                >
                  重新加载
                </button>
              </div>
            ) : rankings.length === 0 ? (
              <div className="flex flex-col justify-center items-center py-16">
                <div className="text-gray-400 text-lg mb-2">📊</div>
                <div className="text-gray-600 mb-4">暂无排行榜数据</div>
                <div className="text-gray-400 text-sm">请稍后再来查看</div>
              </div>
            ) : (
              <ForumRankings rankings={rankings} />
            )}
          </div>
        </div>
      </div>
    </div>
  );
} 